import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Spin, message, Button, Card, Alert, Form, Input, InputNumber, Upload, Icon, Row, Col, Table, Checkbox } from 'antd';
import InputMy from '@/components/Input/index'
import styles from './index.less';
import FromTable from './FromTable'
import router from 'umi/router';


const namespace = 'expresssetting';
@Form.create()
class AddTemp extends Component {
  constructor(props) {
    super(props);

    this.state = {
    };
    this.obj = {
      FirstFee: -1,
      FirstAmount: -1,
      AdditionalFee: -1,
      AdditionalAmount: -1,
    }
  }

  componentWillMount() {
    window.Isoption = false;
  }
  componentDidMount() {
    window.Isoption = true;
  }
  GetInfo = () => {
    const { dispatch } = this.props;

  };
  compareToDefualtFree = (rule, value, callback) => {
    const form = this.props.form;

    // if (!this.obj.AdditionalFee || !this.obj.AdditionalAmount || !this.obj.FirstFee || !this.obj.FirstAmount) {
    //   callback('请设置默认运费');
    // } else if (!/^[1-9]\d*$/.test(this.obj.FirstAmount) || !/^[1-9]\d*$/.test(this.obj.AdditionalAmount)) {
    //   callback('件数请输入正整数');

    // } else if (!/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(this.obj.FirstFee) || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(this.obj.AdditionalFee)) {
    //   callback('请输入正确的金额');

    // } else {
    //   callback()
    // }       
    if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
      callback('默认运费必须填写');
    } else {
      callback()
    }
  }
  compareToValuationRules = (rule, value, callback) => {

    const form = this.props.form;
    callback()

  }
  onChangeDefualtFree = (name, e) => {

    const { form } = this.props;
    this.obj[name] = e;
    form.setFieldsValue({
      DefualtFree: { ...this.obj },
    });
    console.log(form.getFieldValue('DefualtFree'))
  }

  handleSubmit = () => {
    let { dispatch } = this.props;

    this.props.form.validateFields((err, values) => {
      if (!err) {

        values = { ...values, ...this.obj }

        // if (!values.ValuationRules || values.ValuationRules.length < 1) {
        //   message.error('必须选择配送区域')
        //   return;
        // }
        dispatch({
          type: `${namespace}/AddFreightTemplate`,
          param: values,
          callback: {
            success: (data) => {
              message.success("添加成功");
              router.replace({
                pathname: `/${window.storeId}/delivery/express`,
              });
            },
            error: (data) => {
              message.error("添加失败" + data.Msg);
            }
          }
        });
      }
    });
  };

  // 校验默认件数
  validateFirstAmount = (rule, value, callback) => {
    if (this.obj.AdditionalFee != -1 || this.obj.AdditionalAmount != -1 || this.obj.FirstFee != -1 || this.obj.FirstAmount != -1) {
      if (!/^[1-9]\d*$/.test(value) || !/^[1-9]\d*$/.test(value)) {
        callback('件数请输入正整数');
      } else {
        callback()
      }
    } else {
      if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
        callback()
      } else {
        callback('请输入件数');
      }
    }
  }

  //校验默认金额
  validateFirstFee = (rule, value, callback) => {
    if (this.obj.AdditionalFee != -1 || this.obj.AdditionalAmount != -1 || this.obj.FirstFee != -1 || this.obj.FirstAmount != -1) {
      if (!/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value) || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value)) {
        callback('请输入正确的金额');

      } else if (0 > parseFloat(value) || parseFloat(value) > 9999) {
        callback('运费最大可输入9999元');
      }
      else {
        callback()
      }
    } else {
      if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
        callback()
      } else {
        callback('请输入金额');
      }
    }
  }

  // 校验增加的件数
  validateAdditionalAmount = (rule, value, callback) => {
    if (this.obj.AdditionalFee != -1 || this.obj.AdditionalAmount != -1 || this.obj.FirstFee != -1 || this.obj.FirstAmount != -1) {
      if (!/^[1-9]\d*$/.test(value) || !/^[1-9]\d*$/.test(value)) {
        callback('件数请输入正整数');
      } else {
        callback()
      }
    } else {
      if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
        callback()
      } else {
        callback('请输入件数');
      }
    }
  }

  //校验增加的金额
  validateAdditionalFee = (rule, value, callback) => {
    if (this.obj.AdditionalFee != -1 || this.obj.AdditionalAmount != -1 || this.obj.FirstFee != -1 || this.obj.FirstAmount != -1) {
      if (!/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value) || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value)) {
        callback('请输入正确的金额');

      } else if (0 > parseFloat(value) || parseFloat(value) > 9999) {
        callback('运费最大可输入9999元');
      } else {
        callback()
      }
    } else {
      if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
        callback()
      } else {
        callback('请输入金额');
      }
    }
  }

  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
        md: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 9 },
        sm: { span: 9 },
        md: { span: 9 },
      },
    };
    const defaultLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
        md: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 19 },
        sm: { span: 19 },
        md: { span: 19 },
      },
    };


    const {
      getFieldDecorator,
      getFieldsError,
      getFieldError,
      isFieldTouched,
      getFieldValue,

    } = this.props.form;
    const {
      loadbtn,
    } = this.props;

    return (
      <Fragment>
        <Spin spinning={false}>
          <Card bordered={false} className={styles.AddTemplate}>
            <Form >
              <Row>
                <Col>
                  <Form.Item
                    {...formItemLayout}
                    label="模板名称"
                  >
                    {getFieldDecorator('Name', {
                      rules: [{ required: true, message: '模板名称必须填写' }],
                    })(
                      <InputMy maxLength={20} showtotal />
                    )}

                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col>
                  <Form.Item
                    label={<span className={'ant-form-item-required'}>默认运费</span>}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                  >
                    {getFieldDecorator('DefualtFree', {
                      validateTrigger: 'onBlur',
                      rules: [{ validator: this.compareToDefualtFree, }],
                    })(
                      <div>
                        <Row>
                          <Col span={4}>
                            <Form.Item
                              className={styles.innerFormItem}
                            >
                              {
                                getFieldDecorator('FirstAmount', {
                                  validateTrigger: 'onBlur',
                                  rules: [{ validator: this.validateFirstAmount, }
                                  ],
                                })(
                                  <InputMy
                                    addonAfter="件"
                                    maxLength={4}
                                    onChange={(e) => this.onChangeDefualtFree('FirstAmount', e.target.value)}
                                    style={{ width: '100%' }}
                                  />
                                )
                              }
                            </Form.Item>
                          </Col>
                          <Col span={1} >
                            <span className='Text'>&nbsp;内，</span>
                          </Col>
                          <Col span={4}>
                            <Form.Item
                              className={styles.innerFormItem}
                            >
                              {
                                getFieldDecorator('FirstFee', {
                                  validateTrigger: 'onBlur',
                                  rules: [{ validator: this.validateFirstFee, }
                                  ],
                                })(
                                  <InputMy
                                    addonAfter="元"
                                    maxLength={7}
                                    onChange={(e) => this.onChangeDefualtFree('FirstFee', e.target.value)}
                                    style={{ width: '100%' }}
                                  />
                                )
                              }
                            </Form.Item>
                          </Col>
                          <Col span={2} style={{ width: '5em' }}>
                            <span className='Text'>；每增加</span>
                          </Col>
                          <Col span={4}>
                            <Form.Item
                              className={styles.innerFormItem}
                            >
                              {
                                getFieldDecorator('AdditionalAmount', {
                                  validateTrigger: 'onBlur',
                                  rules: [{ validator: this.validateAdditionalAmount, }
                                  ],
                                })(
                                  <InputMy
                                    addonAfter="件"
                                    maxLength={4}
                                    onChange={(e) => this.onChangeDefualtFree('AdditionalAmount', e.target.value)}
                                    style={{ width: '100%' }}
                                  />
                                )
                              }
                            </Form.Item>
                          </Col>
                          <Col span={2} style={{ width: '5em' }}>
                            <span className='Text'>&nbsp;增加运费</span>
                          </Col>
                          <Col span={4}>
                            <Form.Item
                              className={styles.innerFormItem}
                            >
                              {
                                getFieldDecorator('AdditionalFee', {
                                  validateTrigger: 'onBlur',
                                  rules: [{ validator: this.validateAdditionalFee, }
                                  ],
                                })(
                                  <InputMy
                                    addonAfter="元"
                                    maxLength={7}
                                    onChange={(e) => this.onChangeDefualtFree('AdditionalFee', e.target.value)}
                                    style={{ width: '100%' }}
                                  />
                                )
                              }
                            </Form.Item>
                          </Col>
                        </Row>
                      </div>
                    )}
                  </Form.Item>
                </Col>

              </Row>
              <Row>
                <Col>
                  <Form.Item
                    {...defaultLayout}
                    label="指定配送区域"
                  >
                    {getFieldDecorator('ValuationRules', {
                      rules: []
                    })(
                      <FromTable
                        form={this.props.form}
                      />
                    )}

                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={19} offset={4}>
                  {getFieldDecorator('IsDefault', {

                    valuePropName: 'checked',

                  })(
                    <Checkbox  >设为新商品默认模板（新添加的商品支持商家配送时的默认模板）</Checkbox>
                  )}
                </Col>
              </Row>
              <Row>
                <Col span={3} offset={4}>
                  <Button type="primary" onClick={this.handleSubmit} loading={loadbtn}>
                    保存
                </Button>
                </Col>
              </Row>
            </Form>

          </Card>
        </Spin>
      </Fragment>
    );
  }
}
export default connect(({ expresssetting, global, loading }) => ({
  expresssetting,
  oemInfo: global.oemInfo,
  loadbtn: loading.effects['expresssetting/AddFreightTemplate'],
}))(AddTemp);
